﻿using System;
using System.Collections.Generic;
using System.Linq;

using Galaktika.BI.Runtime.Services;

using Ranet.Olap.Core.Data;
using Ranet.Olap.Core;
using Ranet.Olap.Core.Providers;

namespace Galaktika.BI.Silverlight.ClientApp.Web.Runtime.DataAccess
{
    public class MDXQueryExecuter : IQueryExecuter
    {
        public MDXQueryExecuter(ConnectionInfo connection, IBindingContext context)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");
            m_Connection = connection;
            if (context == null)
                throw new ArgumentNullException("context");
            m_Context = context;
        }

        IBindingContext m_Context = null;
        #region IQueryExecuter Members
        ConnectionInfo m_Connection = null;
        public ConnectionInfo Connection
        {
            get
            {
                if (m_Connection == null)
                    m_Connection = new ConnectionInfo();
                return m_Connection;
            }
        }

        public CellSetData ExecuteQuery(string query)
        {
            IExecutionContext exe = (IExecutionContext)m_Context.Services.GetService(typeof(IExecutionContext));
            if (exe != null)
            {
                string parsedConnStr = exe.Parse(m_Context, Connection.ConnectionString);
                string parsedQuery = exe.Parse(m_Context, query);

                CellSetData cellSetData = OlapQueryExecutor.ExecuteQuery(parsedConnStr, parsedQuery, m_Context);
                if (cellSetData != null)
                { 
                    cellSetData.Connection.ConnectionID = Connection.ConnectionID;
                    cellSetData.Connection.ConnectionString = Connection.ConnectionString;
                }
                return cellSetData;
            }

            return null;
        }

        public int ExecuteNonQuery(string query)
        {
            IExecutionContext exe = (IExecutionContext)m_Context.Services.GetService(typeof(IExecutionContext));
            if (exe != null)
            {
                string parsedConnStr = exe.Parse(m_Context, Connection.ConnectionString);
                string parsedQuery = exe.Parse(m_Context, query);

                return OlapQueryExecutor.ExecuteNonQuery(parsedConnStr, parsedQuery);
            }

            return -1;
        }
        #endregion
    }
}
